<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }



</style>
<template>
  <div>

    <el-form :inline="true">
      <el-form-item label="广告位置：">
        <el-select v-model="searchMap.position" placeholder="请输入广告位置关键字搜索" filterable clearable>
          <el-option
            v-for="item in positions"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="fetchData()">查询</el-button>
      <el-button type="primary" @click="handleEdit('')">新增</el-button>
    </el-form>

<!--表格组件-->
<el-table
  :data="list"
  border
  style="width: 100%"
>
  <el-table-column prop="id" label="id" width="205" />
  <el-table-column prop="position" label="位置：" width="120">
    <temlate slot-scope="scope">
           <span v-if="scope.row.position ==0">首页顶部</span>
           <span v-if="scope.row.position ==1">首页中部</span>
    </temlate>
  </el-table-column>
  <el-table-column prop="image" label="图片" width="200">
    <temlate slot-scope="scope">
      <img :src="scope.row.image" min-withd="70" height="70">
    </temlate>
  </el-table-column>
  <el-table-column prop="description" label="描述" width="200" />
  <el-table-column prop="url" label="广告的跳转地址" width="200" />
  <el-table-column prop="created" label="创建时间" width="200" :formatter="dateFormat" />

  <el-table-column
    fixed="right"
    label="操作"
    width="100"
  >
    <template slot-scope="scope">
      <el-button type="text" size="small" @click="handleEdit(scope.row.id)">修改</el-button>
      <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
    </template>
  </el-table-column>
</el-table>

<!--分页-->
<el-pagination
  :current-page="currentPage"
  :page-sizes="[5,10,20]"
  :page-size="pageSize"
  layout="total, sizes, prev, pager, next, jumper"
  :total="total"
  @size-change="sizeData"
  @current-change="pageData"
/>

    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form label-width="80px">
        <el-form-item label="广告位置">
          <el-radio-group v-model="pojo.position">
            <el-radio v-for="item in positions"
                      :key="item.id" :label="item.id">{{ item.value }}
            </el-radio>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/image?folder=banner"
             name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告的跳转地址"><el-input v-model="pojo.url" /></el-form-item>
        <el-form-item label="描述"><el-input v-model="pojo.description" /></el-form-item>
        <el-button type="primary" @click="handleSave()">保存</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </el-form>
    </el-dialog>


  </div>
</template>
<script>

  import bannerApi from '@/api/banner'
  import { getToken } from '@/utils/auth'

  //导入日期组件
  import moment from 'moment'

  export default {
    data() {
      return {
        list: [],
        total: 0, // 总记录数
        currentPage: 1, // 当前页
        pageSize: 10, // 每页大小
        searchMap: {
          pageSize:10,
          page:1
        }, // 查询条件
        dialogFormVisible: false, // 编辑窗口是否可见
        pojo: {}, // 编辑表单绑定的实体对象
        id: '', // 当前用户修改的ID
        imageUrl: '',
        positions:[
          {
            "id":0,
            "value":"首页顶部"
          },
          {
            "id":1,
            "value":"首页中部"
          }
        ],
        headers: { token : getToken() }
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      sizeData(pageSize) {
        console.log(pageSize)
        this.pageSize=pageSize;
        this.searchMap.pageSize=this.pageSize;
        this.fetchData();
      },
      pageData(page) {
        console.log(page)
        this.currentPage=page;
        this.searchMap.page=this.currentPage;
        this.fetchData();
      },
      fetchData() {

        //向后端发起请求
        bannerApi.getList(this.searchMap).then(response => {
          this.list = response.data
          this.total = response.count
        })
      },
      dateFormat:function (row,column) {

        let date=row[column.property]

        if(date == undefined){return ''}

        return moment(date).format('YYYY-MM-DD')

      },
      //点击编辑按钮
      handleEdit(id){

        this.id=id;
        this.dialogFormVisible = true;//打开窗口



        if(id != ''){//修改

          bannerApi.findById(id).then(response => {
            this.pojo = response.data;
            this.imageUrl=this.pojo.image
          });
        }else{
          //新增
          this.pojo={} //清空数据
          this.imageUrl=""
        }
      },
      handleSave(){

        //携带图片路径
        this.pojo.image=this.imageUrl

        bannerApi.update(this.id,this.pojo).then(response=>{

          this.$message({
            message:response.msg,
            type:(response.code==0 ? 'success' : 'error')
          });


          //如果执行成功刷新表单的数据
          if(response.code==0){
            this.fetchData(); //刷新表单
          }

        })

        this.dialogFormVisible = false;//关闭窗口

      },
      handleAvatarSuccess(res, file) {
        //上传图片成功绑定图片的地址
        //this.imageUrl = URL.createObjectURL(file.raw);
        this.imageUrl =  file.response.data;
      },
      beforeAvatarUpload(file) {
        //上传之前校验图片的大小和格式
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleDelete(id){


        this.$confirm('您确定要删除这条记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          bannerApi.delete(id).then(response=>{

            if(response.code===0){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });

              //重新加载列表
              this.fetchData();

            }else{
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }

          })


        })



      }
    }
  }

</script>
